package utils

import (
	"context"
	"errors"
	"fmt"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/tencentyun/cos-go-sdk-v5"
	"io"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"time"
)

type uploadUtils struct {
	client *cos.Client
}

var LocalUploadUtils *uploadUtils

func init() {
	bucket, _ := url.Parse("https://qigeyu-1301040164.cos.ap-nanjing.myqcloud.com")
	service, _ := url.Parse("https://cos.ap-nanjing.myqcloud.com")
	bucketObj := &cos.BaseURL{
		BucketURL:  bucket,
		ServiceURL: service,
	}
	LocalUploadUtils = &uploadUtils{
		client: cos.NewClient(bucketObj, &http.Client{
			Transport: &cos.AuthorizationTransport{
				SecretID:  "AKIDnY9zhVPRLMMUk9l2KQJ3skXDpLj1Mchd",
				SecretKey: "tbAZ65rfp7FB0kMp8EE6rT5d8Tddntqg",
			},
		}),
	}

}
func (u *uploadUtils) FileValidator(file *ghttp.UploadFile) (boolean bool, err error) {
	reg, err := regexp.Compile(`\.(jpg|jpeg|png|gif|bmp|webp|icon)$`)
	if err != nil {
		return false, err
	}
	str := reg.FindAllString(file.Filename, -1)
	return len(str) > 0, nil
}
func (u *uploadUtils) Upload(ctx context.Context, file *ghttp.UploadFile) (url string, err error) {

	if LocalUploadUtils != nil {
		open, err := file.Open()
		if err != nil {
			return "", err
		}
		tempDir := os.TempDir()
		timestamp := fmt.Sprintf("%d", time.Now().Unix())
		tempFile, err := os.CreateTemp(tempDir, "upload_"+file.Filename+"_"+timestamp)
		if err != nil {
			return "", err
		}
		_, err = io.Copy(tempFile, open)
		if err != nil {
			return "", err
		}
		upload, _, err := LocalUploadUtils.client.Object.Upload(ctx, timestamp+"_"+file.Filename, tempFile.Name(), nil)
		if err != nil {
			return "", err
		}
		return upload.Location, nil
	} else {
		return "", errors.New("接口未初始化")
	}
}
func (u *uploadUtils) UploadLocal(ctx context.Context, filename string, filePath string) (url string, err error) {
	if LocalUploadUtils != nil {
		upload, _, err := LocalUploadUtils.client.Object.Upload(ctx, filename, filePath, nil)
		if err != nil {
			return "", err
		}
		return upload.Location, nil
	} else {
		return "", errors.New("接口未初始化")
	}
}
